package com.jack.payment.rabbitmq.consumer;

import com.jack.payment.constant.SettingRuleConstant;
import com.jack.payment.constant.enums.TimeEnum;
import com.jack.payment.dao.user.UserSettingDao;
import com.jack.payment.entity.generate.user.UserSettingModel;
import com.jack.payment.entity.mong.RequestLogModel;
import com.jack.payment.rabbitmq.constant.RabbitmqConstant;
import com.jack.payment.rabbitmq.entity.QueueContentModel;
import com.jack.payment.rabbitmq.produer.MQSender;
import com.jack.payment.service.mongo.QueueLogServiceImpl;
import com.jack.payment.service.mongo.RequestLogServiceImpl;
import com.jack.payment.util.common.StringUtil;
import com.jack.payment.util.common.TimeUtil;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class PaymentRequestReceiver {
    private Logger log = LoggerFactory.getLogger(PaymentRequestReceiver.class);

    @Autowired
    private RequestLogServiceImpl requestLogService;
    @Autowired
    private QueueLogServiceImpl queueLogService;
    @Autowired
    private UserSettingDao userSettingDao;
    @Autowired
    private MQSender mqSender;

    @RabbitListener(queues = RabbitmqConstant.QUEUE_PAYMENT_LOGGER)
    public void requestLoggerRecord(Message message,
                                    QueueContentModel<RequestLogModel> queueModel,
                                    Channel channel) throws IOException {
        log.info("请求日志!! 正在进行队列消费!!! 队列id==>>>{}, 消息主题为==>>{} 已消费了==>>{}次",
                queueModel.getId(), queueModel.getSubject(), queueModel.getCount());
        Long currentTime = TimeUtil.getCurrentTime();
        Integer count = queueModel.getCount();
        queueModel.setCount( count + 1);
        try {
            if (queueModel.getStatus() == 0) {
                String requestLogDBName = TimeUtil.timeFormatJoin(
                        SettingRuleConstant.REQUEST_LOG,
                        queueModel.getSendDate(),
                        TimeEnum.MONTH
                        );
                RequestLogModel requestLogModel = queueModel.getData();
                requestLogService.saveRequestLog(requestLogModel, requestLogDBName);
                if (requestLogModel.getRequestType() == 2 && !StringUtil.isEmpty(requestLogModel.getUserId())) {
                    userSettingUpdate(requestLogModel);
                }
                queueModel.setStatus(1);
                queueModel.setSuccessDate(currentTime);
            }
        } catch (Exception e) {
            log.error("日志记录失败!!!" + e);
            log.error("队列id=>>{}, 对应集合=>>{}", queueModel.getId(), queueModel.getDbName());
            queueModel.setExceptionInfo(e.getMessage());
            if (count < 2 && queueModel.getIsManual() == 0) {
                log.info("消息消费失败!!! 正在进行重发, 当前已发送{}次, 总共发送2次", count);
                mqSender.sendMQMessage(
                        queueModel.getExchange(),
                        queueModel.getQueueName(),
                        queueModel
                        );
            }
        } finally {
            queueModel.setLastDate(currentTime);
            queueLogService.updateQueueLog(queueModel, queueModel.getDbName());
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    /**
     * 用户登录日志
     * @param requestLogModel
     */
    private void userSettingUpdate(RequestLogModel requestLogModel) {
        UserSettingModel userSettingModel = new UserSettingModel();
        userSettingModel.setUserId(requestLogModel.getUserId());
        userSettingModel.setIpAddress(requestLogModel.getRequestIp());
        userSettingModel.setLastOneTime(requestLogModel.getCreateTime());
        userSettingDao.updateAppointUserSetting(userSettingModel);
    }

}
